package quick.portal.activity;

import java.io.IOException;

import quick.common.AppContext;
import quick.common.AppManager;
import quick.common.SharedPreferences;
import quick.common.UIHelper;
import quick.communication.AsyncHttpResponseHandler;
import quick.portal.R;
import quick.portal.data.APIResult;
import quick.portal.data.UserInfo;
import quick.portal.service.UserInfoService;

import com.alibaba.fastjson.JSON;
import com.squareup.okhttp.Request;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;

public class SplashActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.splash_activity);
		
		AppManager.getAppManager().addActivity(this);
		
		this.autoLogin();
	}
	
	@Override
    protected void onDestroy() {
        super.onDestroy();
        
        // 结束Activity从堆栈中移除
        AppManager.getAppManager().finishActivity(this);
    }

	private void autoLogin()
    {
    	String token = SharedPreferences.getInstance().getString(AppContext.USERINFO_TOKEN, "");

    	if(token=="") 
    	{
    		UIHelper.showActivity(SplashActivity.this, LoginActivity.class);
    		return;
    	}
    	
    	final ProgressDialog pd = ProgressDialog.show(this, "", "自动登陆中...");
    	
    	new UserInfoService().login(token, new AsyncHttpResponseHandler()
        {
    		@Override
            public void onSuccess(String body) 
    		{
    			pd.dismiss();
    			
    			try
        		{
        			APIResult result = JSON.parseObject(body, APIResult.class);

        			if(result.getReturnCode()==0)
    	        	{
        				UserInfo user = JSON.parseObject(result.getBody(), UserInfo.class);
        				AppContext.getInstance().setUserInfo(user.getName(),result.getMessage());
        				UIHelper.showActivity(SplashActivity.this, MainActivity.class);
        				       				
    	        	}
        			else
        			{
        				UIHelper.showActivity(SplashActivity.this, LoginActivity.class);
        			}
        		}
	        	catch(Exception ex)
	        	{
	        		UIHelper.showActivity(SplashActivity.this, LoginActivity.class);	        		
	        	}
    		}
    		
    		@Override
            public void onFailure(Request request, IOException e) {
    			pd.dismiss();
    			UIHelper.showActivity(SplashActivity.this, LoginActivity.class);
            }
        });
    }
}
